package com.kudian.restful.controller;

import com.kudian.common.exception.ApplicationException;
import com.kudian.common.persistence.Page;
import com.kudian.common.persistence.ResultObj;
import com.kudian.common.utils.DateUtils;
import com.kudian.common.utils.JsonUtils;
import com.kudian.common.utils.StringUtils;
import com.kudian.restful.entity.Goods;
import com.kudian.restful.entity.LoginSession;
import com.kudian.restful.entity.Seller;
import com.kudian.restful.service.GoodsService;
import com.kudian.restful.service.LoginSessionService;
import com.kudian.restful.service.SellerService;
import com.kudian.restful.vo.goods.*;
import com.kudian.restful.vo.seller.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/4/17.
 */
@RestController
@RequestMapping("goods")
public class GoodsController {
    private static final Logger logger = Logger.getLogger(GoodsController.class);

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private LoginSessionService loginSessionService;

    @RequestMapping(value = "add", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "创建商品信息", httpMethod = "POST", notes = "商品信息以json格式传递", response = AddGoodsRetVO.class)
    public @ResponseBody AddGoodsRetVO add(@RequestBody AddGoodsVO addGoodsVO) {
        logger.info("add=>" + JsonUtils.toJson(addGoodsVO));
        AddGoodsRetVO o = new AddGoodsRetVO();
        if (addGoodsVO == null || StringUtils.isBlank(addGoodsVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("创建商品信息失败!access_token为空");
            return o;
        }

        try {

            Integer goodsid = goodsService.saveGoodsAndPics(addGoodsVO);
            // 成功
            o.setErrcode(0);
            o.setErrmsg("创建商品信息成功!");
            o.setGoodsId(goodsid);
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("创建商品信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "修改商品信息", httpMethod = "POST", notes = "修改商品信息", response = AddGoodsRetVO.class)
    public @ResponseBody AddGoodsRetVO update(@RequestBody UpdateGoodsVO updateGoodsVO) {
        logger.info("update=>" + JsonUtils.toJson(updateGoodsVO));
        AddGoodsRetVO o = new AddGoodsRetVO();

        try {
            if (updateGoodsVO == null || StringUtils.isBlank(updateGoodsVO.getAccess_token())) {
                o.setErrcode(9999);
                o.setErrmsg("修改商品信息失败!access_token为空");
                return o;
            }

            Integer goodsid = goodsService.updateGoodsAndPics(updateGoodsVO);
            // 成功
            o.setErrcode(0);
            o.setErrmsg("修改商品信息成功!");
            o.setGoodsId(goodsid);
        } catch (ApplicationException e) {
            o.setErrcode(e.getErrcode());
            o.setErrmsg(e.getErrmsg());
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("修改商品信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "off", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "商品下架", httpMethod = "POST", notes = "商品下架", response = ResultObj.class)
    public @ResponseBody ResultObj off(@RequestBody OffGoodsVO offGoodsVO) {
        ResultObj o = new ResultObj();

        try {
            if (offGoodsVO == null || StringUtils.isBlank(offGoodsVO.getAccess_token())) {
                o.setErrcode(9999);
                o.setErrmsg("商品下架失败!access_token为空");
                return o;
            }
            LoginSession ent = this.loginSessionService.getInfo(offGoodsVO.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }

            goodsService.off(offGoodsVO);
            // 成功
            o.setErrcode(0);
            o.setErrmsg("商品下架成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("商品下架失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除商品", httpMethod = "POST", notes = "删除商品", response = ResultObj.class)
    public @ResponseBody ResultObj delete(@RequestBody DelGoodsVO delGoodsVO) {
        ResultObj o = new ResultObj();

        try {
            if (delGoodsVO == null || StringUtils.isBlank(delGoodsVO.getAccess_token())) {
                o.setErrcode(9999);
                o.setErrmsg("删除商品失败!access_token为空");
                return o;
            }
            LoginSession ent = this.loginSessionService.getInfo(delGoodsVO.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }

            goodsService.delete(delGoodsVO);
            // 成功
            o.setErrcode(0);
            o.setErrmsg("删除商品成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("删除商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "on", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "上架商品", httpMethod = "POST", notes = "上架商品", response = ResultObj.class)
    public @ResponseBody ResultObj on(@RequestBody OnGoodsVO onGoodsVO) {
        ResultObj o = new ResultObj();

        try {
            if (onGoodsVO == null || StringUtils.isBlank(onGoodsVO.getAccess_token())) {
                o.setErrcode(9999);
                o.setErrmsg("商品上架失败!access_token为空");
                return o;
            }
            LoginSession ent = this.loginSessionService.getInfo(onGoodsVO.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }

            goodsService.on(onGoodsVO);
            // 成功
            o.setErrcode(0);
            o.setErrmsg("商品上架成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("商品上架失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "query", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
         @ApiOperation(value = "取得商品信息", httpMethod = "POST", notes = "商品信息以json格式传递", response = QueryGoodsRetVO.class)
    public @ResponseBody QueryGoodsRetVO query(@RequestBody QueryGoodsVO queryGoodsVO) {
        logger.info("query=>" + JsonUtils.toJson(queryGoodsVO));
        QueryGoodsRetVO o = new QueryGoodsRetVO();
        if (queryGoodsVO == null || StringUtils.isBlank(queryGoodsVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("取得商品信息失败!access_token为空");
            return o;
        }

        try {
            o.setGoodsinfos(goodsService.goodsByCategory(goodsService.queryGoodsAndPics(queryGoodsVO)));
            o.setErrcode(0);
            o.setErrmsg("取得商品信息成功!");
        } catch (ApplicationException e) {
            o.setErrcode(e.getErrcode());
            o.setErrmsg(e.getErrmsg());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得商品信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "details", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得商品明细", httpMethod = "POST", notes = "", response = DetailGoodsRetVO.class)
    public @ResponseBody DetailGoodsRetVO details(@RequestBody DetailGoodsVO detailGoodsVO) {
        logger.info("details=>" + JsonUtils.toJson(detailGoodsVO));
        DetailGoodsRetVO o = new DetailGoodsRetVO();
        try {
            GoodsItemVO item = this.goodsService.details(detailGoodsVO.getGoodsId());
            if (item != null) {
                int collectionId = this.goodsService.isCollection(detailGoodsVO.getAccess_token(), detailGoodsVO.getGoodsId());
                if (0 == collectionId) {
                    item.setIsCollect(false);
                    item.setCollectionId(0);
                } else {
                    item.setIsCollect(true);
                    item.setCollectionId(collectionId);
                }
            }
            o.setInfo(item);
            o.setErrcode(0);
            o.setErrmsg("取得商品明细成功!");
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得商品明细失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    // ------------ 以下是客户端查询 ------- //
    @RequestMapping(value = "viewSpeGoods", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得特产商品", httpMethod = "GET", notes = "", response = SepGoodsRetVO.class)
    public SepGoodsRetVO viewSpeGoods() {
        logger.info("viewSpeGoods=>");
        SepGoodsRetVO o = new SepGoodsRetVO();
        try {
            // 第一页,为了适应之前的接口形态
            Page<GoodsItemVO> page = goodsService.spedetails(1);
            o.setItems(page.getResult());
            o.setErrcode(0);
            o.setErrmsg("取得特产商品成功!");
            o.setHasNext(page.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得特产商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "viewSpeGoods/{pageNo}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得特产商品", httpMethod = "GET", notes = "", response = SepGoodsRetVO.class)
    public SepGoodsRetVO viewSpeGoods(@PathVariable("pageNo") Integer pageNo) {
        logger.info("viewSpeGoods=>");
        SepGoodsRetVO o = new SepGoodsRetVO();
        try {
            Page<GoodsItemVO> page = goodsService.spedetails(pageNo);
            o.setItems(page.getResult());
            o.setErrcode(0);
            o.setErrmsg("取得特产商品成功!");
            o.setHasNext(page.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得特产商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "viewSpeGoodsInHomepage", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得显示在首页上的特产商品", httpMethod = "GET", notes = "", response = SepGoodsRetVO.class)
    public SepGoodsRetVO viewSpeGoodsInHomepage() {
        logger.info("viewSpeGoods=>");
        SepGoodsRetVO o = new SepGoodsRetVO();
        try {
            o.setItems(goodsService.spedetailsinhomepage());
            o.setErrcode(0);
            o.setErrmsg("取得特产商品成功!");
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得特产商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryByclient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "在客户端取得某一店铺商品", httpMethod = "POST", notes = "在客户端取得商品", response = QueryGoodsRetVO.class)
    public @ResponseBody QueryGoodsRetVO queryByclient(@RequestBody QueryGoodsByClientVO vo) {
        logger.info("queryByclient=>" + JsonUtils.toJson(vo));
        QueryGoodsRetVO o = new QueryGoodsRetVO();
        try {
            Page<GoodsItemVO> goods = goodsService.queryGoodsBySellerId(vo.getSellerId(), vo.getPageNo());
            o.setGoodsinfos(goodsService.goodsByCategory(goods.getResult()));

            o.setErrcode(0);
            o.setErrmsg("客户端取得某一店铺商品成功!");
            o.setHasNext(goods.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("客户端取得某一店铺商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryByCatClient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "在客户端取得某一店铺商品, 按商品分类取得", httpMethod = "POST", notes = "在客户端取得某一店铺商品, 按商品分类取得", response = QueryGoodsRetVO.class)
    public @ResponseBody QueryGoodsRetVO queryByCatClient(@RequestBody QueryGoodsByCatClientVO vo) {
        logger.info("queryByclient=>" + JsonUtils.toJson(vo));
        QueryGoodsRetVO o = new QueryGoodsRetVO();
        try {
            Page<GoodsItemVO> goods = goodsService.queryGoodsBySellerId(vo.getSellerId(), vo.getPageNo(), vo.getCatId());
            o.setGoodsinfos(goodsService.goodsByCategory(goods.getResult()));

            o.setErrcode(0);
            o.setErrmsg("客户端按商品分类取得某一店铺商品成功!");
            o.setHasNext(goods.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("客户端按商品分类取得某一店铺商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryByGroupclient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "在客户端取得某一店铺商品,按团属性取得", httpMethod = "POST", notes = "", response = QueryGoodsRetVO.class)
    public @ResponseBody QueryGoodsRetVO queryByGroupclient(@RequestBody QueryGoodsByGroupClientVO vo) {
        logger.info("queryByGroupclient=>" + JsonUtils.toJson(vo));
        QueryGoodsRetVO o = new QueryGoodsRetVO();
        try {
            Page<GoodsItemVO> goods = goodsService.queryGoodsBySellerIdAndGroupId(vo.getSellerId(), vo.getGbTypeId(), vo.getPageNo());
            o.setGoodsinfos(goodsService.goodsByCategory(goods.getResult()));

            o.setErrcode(0);
            o.setErrmsg("客户端取得某一店铺团商品成功!");
            o.setHasNext(goods.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("客户端取得某一店铺团商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryAroundByclient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得周边商铺商品", httpMethod = "POST", notes = "取得周边商铺商品", response = QueryGoodsAroundRetVO.class)
    public @ResponseBody QueryGoodsAroundRetVO queryAroundByclient(@RequestBody GoodsAroundVO vo) {
        logger.info("queryAroundByclient=>" + JsonUtils.toJson(vo));
        QueryGoodsAroundRetVO o = new QueryGoodsAroundRetVO();
        try {
            if (StringUtils.isBlank(vo.getLatitudes()) || StringUtils.isBlank(vo.getLongitudes())) {
                // 失败
                o.setErrcode(9999);
                o.setErrmsg("请重新定位坐标!");
                return o;
            }

            Page<GoodsAroundItemVO> goodses = goodsService.queryAroundByclient(vo);
            o.setGoodsinfos(goodses.getResult());
            o.setErrcode(0);
            o.setErrmsg("取得周边商铺商品成功!");
            o.setHasNext(goodses.isHasNext());
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得周边商铺商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryConditionAroundByclient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得周边商铺商品--条件筛选", httpMethod = "POST", notes = "取得周边商铺商品--条件筛选", response = QueryGoodsAroundRetVO.class)
    public @ResponseBody QueryGoodsAroundRetVO queryConditionAroundByclient(@RequestBody GoodsAroundConditionVO vo) {
        logger.info("queryConditionAroundByclient=>" + JsonUtils.toJson(vo));
        QueryGoodsAroundRetVO o = new QueryGoodsAroundRetVO();
        try {
            GoodsAroundVO v = new GoodsAroundVO();
            v.setGtId(vo.getGtId());
            v.setLatitudes(vo.getLatitudes());
            v.setLongitudes(vo.getLongitudes());

            Page<GoodsAroundItemVO> goodses = goodsService.queryAroundByclient(v);
            o.setGoodsinfos(goodses.getResult());
            o.setErrcode(0);
            o.setErrmsg("取得周边商铺商品成功!");
        } catch (Exception e) {
            o.setErrcode(9999);
            o.setErrmsg("取得周边商铺商品失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }
}
